from custom_widgets import TinyMCE
from django import forms as forms
from django.forms import ModelForm
from django.forms.widgets import Textarea
from django.forms.fields import CharField
from blogs.models import Blog, Post, Comment, Link
from django.conf import settings
import blogs.captcha

class AddPostForm(ModelForm):
    '''
        Torm for adding new posts to a blog.
    '''
    body = forms.CharField(widget=TinyMCE())
    body.widget.mce_settings = body.widget.update_settings(settings.POST_EDITOR_MODE)
    tags_str = forms.RegexField('[a-zA-Z0-9]+(\s[a-zA-Z0-9]+)*', label='Tags', required=False, help_text='Tags for this post, separated by a space (" ")',)
    comments_enabled = forms.BooleanField(initial=True,help_text='Enable readers to comment on this post.')
    
    class Meta:
        model = Post
        fields = ('title', 'slug', 'body', 'image')
    
    def clean_slug(self):
        try:
            post = Post.objects.get(slug=self.cleaned_data['slug'])
        except Post.DoesNotExist:
                return self.cleaned_data['slug']
        raise forms.ValidationError('This slug already exists. Try adding more letters or numbers.')


class EditPostForm(ModelForm):
    '''
        Torm for editing posts on a blog.
    '''
    body = forms.CharField(widget=TinyMCE())
    body.widget.mce_settings = body.widget.update_settings(settings.POST_EDITOR_MODE)
    tags_str = forms.RegexField('[a-zA-Z0-9]+(\s[a-zA-Z0-9]+)*', label='Tags', required=False, help_text='Tags for this post, separated by a space (" ")',)
    comments_enabled = forms.BooleanField(help_text='Enable readers to comment on this post.')
    
    class Meta:
        model = Post
        fields = ('title', 'slug', 'body', 'image',)


BLOG_EDITOR_MODE = {
    'mode': 'textareas',
    'theme': 'simple',
    'width': '500',
}

class BlogDetailsForm(ModelForm):
    '''
        Form for editing options for a blog.
    '''
    description = forms.CharField(widget=TinyMCE())
    description.widget.mce_settings = description.widget.update_settings(BLOG_EDITOR_MODE)

    class Meta:
        model = Blog
        exclude = ('slug','users',)
    
    def clean_at_most(self):
        if self.cleaned_data['at_most'] > 0:
            return self.cleaned_data['at_most']
        else:
            raise forms.ValidationError('Enter a value greater than zero.')

class CommentForm(ModelForm):
    '''
        Form for editing a post comment.
    '''
    email = forms.CharField(help_text='(will not be posted)')
    website = forms.CharField(required=False)
    
    class Meta:
        model = Comment
        fields = ('name', 'email', 'website', 'message')

class LinkForm(ModelForm):
    '''
        Form for editing a post comment.
    '''
    class Meta:
        model = Link
        fields = ('name','url','tooltip', 'active')